// pages/userLogin/login.js
import Dialog from '../../miniprogram_npm/weapp/dialog/dialog';
import { formatTime } from '../../utils/util';
const db = wx.cloud.database();
const user = db.collection('user')
const points = db.collection('points');
const app = getApp();
Page({
  data: {
    username: "",
    password: "",
    userNameerrorMsg: '',
    userPassworderrorMsg: '',
    checkbox: false,
    protectionAgreementUrl: "https://mp.weixin.qq.com/s/PYch4DhfiovqHvdqahYqqg",
    serviceAgreementUrl: "",
    tabsIndex: 0,
    //注册信息
    register_username: '',
    userName_registerError: '',
    register_password: '',
    userPassword_registerError: '',
    register_checkPassword: '',
    checkPassword_registerError: ''
  },
  loginBack() {
    wx.navigateBack({
      delta: 1,
    })
  },

  isRead() {
    //弹出框的操作，格外调用组件
    const beforeClose = (action) => new Promise((resolve) => {
      setTimeout(() => {
        if (action === 'confirm') {
          this.setData({
            checkbox: true,
          });
          resolve(true);
        } else {
          // 拦截取消操作
          this.setData({
            checkbox: false,
          });
          resolve(true);
        }
      }, 1000);
    });

    Dialog.confirm({
      title: "服务协议及隐私保护",
      message: "  为了更好地保障你的合法权益，请你阅读并同意一下协议 《鲤鱼科技隐私保护政策》《鲤鱼科技在线服务协议》",
      confirmButtonText: "同意",
      cancelButtonText: "不同意",
      beforeClose
    });
  },
  getUserInfo(e) {
    let that = this;
    wx.login({
      success(res) {
        that.register(e.detail.userInfo)
      }
    })
  },

  login() {
    var that = this;
    if (this.data.username == '') {
      this.setData({
        userNameerrorMsg: "请输入用户名"
      })
    } else {
      this.setData({
        userNameerrorMsg: ''
      })
    }
    if (this.data.password == '') {
      this.setData({
        userPassworderrorMsg: "密码不能为空"
      })
    } else if (this.data.checkbox == false) {
      this.isRead()
    } else if (this.data.username != '' && this.data.password != '') {
      wx.cloud.callFunction({
        name: "login"
      }).then(loginRes => {
        //console.log(res.result.openid)
        user.where({
          _openid: loginRes.result.openid
        }).get().then(res => {
          if (res.data.length > 0) {
            if (this.data.username == res.data[0].username && this.data.password == res.data[0].userpassword) {
              app.setGlobalUserInfo(res.data[0]);
              //积分添加
              points.add({
                data: {
                  title: "登录",
                  addTime: formatTime(new Date()),
                  addORminus: 1//加还是减
                }
              })
              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 3000
              })

              setTimeout(function () {
                wx.reLaunch({
                  url: '../user/user',
                  success() {
                    var page = getCurrentPages().pop();
                    if (page == undefined || page == null) return;
                    page.onLoad();
                  }
                });
              }, 3000)
            } else {
              wx.showToast({
                title: '用户名或者密码不对',
                icon: 'error',
                duration: 2000
              })
            }
          } else {
            wx.showToast({
              title: '账号不存在',
              icon: 'error',
              duration: 1000
            }),
              that.setData({
                tabsIndex: 1
              })
          }
        });
        this.setData({
          userPassworderrorMsg: ''
        })
      })
    }
  },

  /**注册按钮 */
  register(u) {
    var that = this;
    if (this.data.register_username == '') {
      var userName_registerError = "用户名不能为空"
    } else {
      userName_registerError = ''
    }
    if (this.data.register_password == '') {
      var userPassword_registerError = "密码不能为空"
    } else {
      userPassword_registerError = ''
    }
    if (this.data.register_checkPassword == '') {
      var checkPassword_registerError = "确认密码不能为空"
    } else if (this.data.register_checkPassword != this.data.register_password) {
      checkPassword_registerError = '确认密码不对'
    } else if (!this.data.checkbox) {
      this.isRead()
    } else if (this.data.register_username != '' && this.data.register_password != '') {
      checkPassword_registerError = ''
      wx.cloud.callFunction({
        name: "login"
      }).then(res => {
        //console.log(res.result.openid)
        user.where({
          _openid: res.result.openid
        }).get().then(getRes => {
          //console.log(getRes)
          if (getRes.data.length > 0) {
            wx.showToast({
              title: '你已存在账号',
              icon: "error",
              duration: 2000
            })
            that.setData({
              tabsIndex: 0,
              register_username: '',
              register_password: '',
              register_checkPassword: ''
            })
          } else {
            wx.showLoading({
              title: '注册中...',
            })
            user.add({
              data: {
                username: this.data.register_username,
                userpassword: this.data.register_password,
                createTime: formatTime(new Date()),
                avatarUrl: u.avatarUrl,
                wxName: u.nickName,
                sex: (u.gender == 0 ? "男" : "女"),
                hobby: "",
                about: "",
                points: [],//积分id
                setting_msg: [],//消息id
                collect: [],//收藏id
                pointsExchange: []//积分兑换id
              },
              success(res) {
                wx.hideLoading({
                  success: () => {
                    wx.showToast({
                      title: '注册成功',
                      icon: 'success',
                      duration: 2000
                    })
                  },
                })

                setTimeout(() => {
                  that.setData({
                    tabsIndex: 0,
                    register_username: '',
                    register_password: '',
                    register_checkPassword: '',
                  })
                }, 2000)

              }
            })
          }
        })
      });

    }
    this.setData({
      userName_registerError,
      userPassword_registerError,
      checkPassword_registerError
    })

  },

  /*
    wxLogin(ee) {
      // console.log(ee.detail.errMsg);
      //console.log(ee.detail.userInfo)
      //console.log(ee.detail.rawData)
      if (ee.detail.errMsg == "getUserProfile:ok") {
        wx.login({
          success(res) {
            console.log(ee.detail.userInfo)
            // app.setGlobalUserInfo(ee.detail.userInfo);
            // wx.showToast({
            //   title: '登录成功',
            //   icon: 'success',
            //   duration: 3000
            // })
            // setTimeout(function () {
            //   wx.reLaunch({
            //     url: '../user/user',
            //     success() {
            //       var page = getCurrentPages().pop();
            //       if (page == undefined || page == null) return;
            //       page.onLoad();
            //     }
            //   });
            // }, 3000)
            //登录的临时凭证
            /*var code = res.code;
            //调用后端，获取微信的session_key,secret
            wx.request({
              url: 'springBoot的后端地址url',
              method: "POST",
              success: function (result) {
                console.log(result)
                app.setGlobalUserInfo(ee.detail.userInfo);
                wx.switchTab({
                  url: '../user/user',
                })
              }
            }) 
          },
        })
      } else {
        wx.showToast({
          title: '登录失败',
          icon: 'error',
          duration: 2000
        })
      }
  
    },*/
  /**
   * 单选按钮事件
   */
  onChange(event) {
    //console.log(event)
    this.setData({
      checkbox: event.detail,
    });
  },

  /**
   * 保护政策跳转
   */
  protectionAgreement() {
    wx.navigateTo({
      url: '/pages/content/content?articleId=privacy',
    })
  },

  /**
   * 服务协议跳转
   */
  serviceAgreement() {
    wx.navigateTo({
      url: '/pages/content/content?articleId=privacy',
    })
  },
  /**tabs切换事件 */
  tabs({ detail }) {
    this.setData({
      tabsIndex: detail.index
    })
  },
})